package com.qifan.energy.activity;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.EnvUtils;
import com.qifan.energy.base.BaseActivity;
import com.qifan.energy.bean.result.AddressItem;
import com.qifan.energy.bean.result.CartListResult;
import com.qifan.energy.bean.result.PayOrderWechatResult;
import com.qifan.energy.bean.vo.GenerateOrderParamVO;
import com.qifan.energy.BuildConfig;
import com.qifan.energy.R;
import com.qifan.energy.adapter.ConfirmOrderAdapter;
import com.qifan.energy.bean.result.CouponItem;
import com.qifan.energy.bean.result.GenerateOrderResult;
import com.qifan.energy.bean.result.MemberInfo;
import com.qifan.energy.global.Keys;
import com.qifan.energy.global.Values;
import com.qifan.energy.http.net.NetUtils;
import com.qifan.energy.http.response.MyObserver;
import com.qifan.energy.util.ActivityStackUtil;
import com.qifan.energy.util.CheckUtil;
import com.qifan.energy.util.IntentUtils;
import com.qifan.energy.util.SharedPreferencesUtil;
import com.qifan.energy.util.ToastUtils;
import com.qifan.energy.util.UIUtils;
import com.qifan.energy.util.eventbus.EventBusUtils;
import com.qifan.energy.util.eventbus.EventCode;
import com.qifan.energy.util.eventbus.EventMessage;
import com.qifan.energy.widget.dialog.LoadingUtils;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ConfirmOrderActivity extends BaseActivity {

    @BindView(R.id.recevier_name_tv)
    TextView recevierNameTv;
    @BindView(R.id.recevier_phone_tv)
    TextView recevierPhoneTv;
    @BindView(R.id.recevier_address_tv)
    TextView recevierAddressTv;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.total_amount_tv)
    TextView totalAmountTv;

    private List<CartListResult> dataList = new ArrayList();
    private GenerateOrderResult generateOrderResult = null;
    private int memberReceiveAddressId = -1;//地址Id
    private CouponItem currentCouponItem = null;
    private IWXAPI wxapi;
    private boolean isClickable = true;//默认可以点击

    /*@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order);
    }*/

    @Override
    protected int getLayoutId() {
        return R.layout.activity_confirm_order;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        //沙箱测试环境
        EnvUtils.setEnv(EnvUtils.EnvEnum.ONLINE);
        /* 更改状态栏 */
        changeStatusTransparentFontBlack();

        /* 跳转传值 接收值 */
        List<CartListResult> data = (List)getIntent().getSerializableExtra(Keys.CART_ORDER_TYPE);
        Logger.i("++++" + data);
        dataList = data;

        /* 适配器设置 */
        ConfirmOrderAdapter adapter = new ConfirmOrderAdapter(dataList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void initData() {
        //获取默认地址
        memberAddressDefaultAddress();
    }

    /* 更新地址信息 */
    private void setUpUIWithAddressInfo(AddressItem item){
        String address = String.format("收货地址：%s%s%s%s",item.getProvince(),item.getCity(),item.getRegion(),item.getDetailAddress());
        recevierNameTv.setText("收货人：" + item.getName());
        recevierPhoneTv.setText(item.getPhoneNumber());
        recevierAddressTv.setText(address);
    }

    /* 获取默认地址 */
    private void memberAddressDefaultAddress(){
        NetUtils.memberAddressDefaultAddress(new MyObserver<AddressItem>(this) {
            @Override
            public void onSuccess(AddressItem result) {
                if (null == result || TextUtils.isEmpty(result.getName()) || TextUtils.isEmpty(result.getDetailAddress()) ){
                    MemberInfo memberInfo = SharedPreferencesUtil.getData(Keys.USER_INFO_MEMBER_KEY,new MemberInfo());
                    if (null != memberInfo) {
                        recevierNameTv.setText("收货人：" + memberInfo.getUsername());
                        recevierPhoneTv.setText(memberInfo.getPhone());
                    }
                    Intent intent = new Intent();
                    intent.putExtra(Keys.ADRESS_ORDER_TYPE, 1);
                    IntentUtils.startActivityForResult(ConfirmOrderActivity.this,AddressListActivity.class,intent,1);
                } else {
                    memberReceiveAddressId = result.getId();
                    setUpUIWithAddressInfo(result);
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    @OnClick(R.id.address_current_ll)
    void onAddressCurrentLlClicked(){
        /* 跳转收货地址列表 */
        Intent intent = new Intent();
        intent.putExtra(Keys.ADRESS_ORDER_TYPE, 1);
        IntentUtils.startActivityForResult(this,AddressListActivity.class,intent,Values.REQUEST_CODE_1);
    }

    @OnClick(R.id.confirm_tv)
    void onConfirmTvClicked(TextView confirmTv){
        /*FastPayUtil.create(this).setPayResultListener(this).alPay(1);*/
        if (CheckUtil.isEmpty(dataList)){
            ToastUtils.showShort("您的购物列表为空哦~");
            return;
        }
        if (memberReceiveAddressId < 0){
            ToastUtils.showShort("请您先获取收货地址");
            return;
        }

        /* 防止暴击生成多次订单 */
        confirmTv.setClickable(false);
        if (isClickable){
            orderGenerateOrder();
        }
        UIUtils.getHandler().postDelayed(()->{
            confirmTv.setClickable(true);
        },2000);
    }

    //生成订单
    private void orderGenerateOrder(){
        isClickable = false;
        LoadingUtils.show(this);
        GenerateOrderParamVO orderParamVO = new GenerateOrderParamVO();
        orderParamVO.setMemberReceiveAddressId(memberReceiveAddressId);
        orderParamVO.setPayType(Values.PayType.ALIPAY);
        List<Integer> cartIds = new ArrayList<>();
        for (CartListResult result : dataList){
            cartIds.add(result.getId());
        }
        orderParamVO.setCartIds(cartIds);
        if (null != currentCouponItem){//优惠券
            orderParamVO.setCouponId(currentCouponItem.getCouponId());
        }
        NetUtils.orderGenerateOrder(orderParamVO ,new MyObserver<GenerateOrderResult>(this) {
            @Override
            public void onSuccess(GenerateOrderResult result) {
                //赋值订单信息
                generateOrderResult = result;
                //通知刷新购物车
                EventBusUtils.post(new EventMessage<>(EventCode.EVENT_1, "EventData"));

                //获取签名信息
                GenerateOrderParamVO orderParamVO = new GenerateOrderParamVO();
                orderParamVO.setOrderId(result.getOrder().getId());
                //orderParamVO.setPayType(Values.PayType.ALIPAY);//支付宝
                //orderAlipay(orderParamVO);
                orderParamVO.setPayType(Values.PayType.WEIXIN);//微信支付
                orderWXPay(orderParamVO);
                isClickable = true;
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LoadingUtils.hide();
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    //生成订单签名信息(支付宝)
    /*private void orderAlipay(final GenerateOrderParamVO orderParamVO){
        NetUtils.orderAlipay(orderParamVO,new MyObserver<String>(this) {
            @Override
            public void onSuccess(String result) {
                Logger.i("paySign:" + result);
                if (!TextUtils.isEmpty(result)){
                    executePayAsyncTask(result);
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LoadingUtils.hide();
                ToastUtils.showShort(errorMsg);
            }
        });
    }*/

    //生成订单签名信息(微信)
    private void orderWXPay(final GenerateOrderParamVO orderParamVO){
        NetUtils.orderWXPay(orderParamVO,new MyObserver<PayOrderWechatResult>(this) {
            @Override
            public void onSuccess(PayOrderWechatResult result) {
                Logger.i("paySign:" + result.toString());
                //FastPayUtil.create(ConfirmOrderActivity.this).startWechatPay(result);
                //调起微信支付
                startWechatPay(result);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LoadingUtils.hide();
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    /* 发起微信支付 */
    public void startWechatPay(PayOrderWechatResult result) {
        //这里的appid，替换成自己的即可
        wxapi = WXAPIFactory.createWXAPI(this,BuildConfig.WX_APPKEY,true);
        wxapi.registerApp(BuildConfig.WX_APPKEY);
        //这里的bean，是服务器返回的json生成的bean
        PayReq payRequest = new PayReq();
        payRequest.appId = result.getAppid();
        payRequest.nonceStr = result.getNoncestr();
        payRequest.partnerId = result.getPartnerid();
        payRequest.prepayId = result.getPrepayid();
        payRequest.packageValue = result.getPackageValue();//固定值
        payRequest.sign = result.getSign();
        payRequest.signType = result.getSignType();
        payRequest.timeStamp = result.getTimestamp();

        //发起请求，调起微信前去支付
        boolean isSuccess = wxapi.sendReq(payRequest);
        if (isSuccess){
            SharedPreferencesUtil.putData(Keys.ORDER_ID_KEY,generateOrderResult.getOrder().getId());
            LoadingUtils.hide();
        } else {
            LoadingUtils.hide();
            ToastUtils.showShort("支付失败");
            ActivityStackUtil.finishTopActivity();
        }
    }

    //必须是异步的调用客户端支付接口
    /*private void executePayAsyncTask(String paySign){
        final PayAsyncTask payAsyncTask = new PayAsyncTask(ConfirmOrderActivity.this, new IAlPayResultListener() {
            @Override
            public void onPaySuccess() {
                GenerateOrderParamVO orderParamVO = new GenerateOrderParamVO();
                orderParamVO.setOrderId(generateOrderResult.getOrder().getId());
                orderParamVO.setPayType(Values.PayType.ALIPAY);
                paySuccess(orderParamVO);
            }

            @Override
            public void onPaying() {
                ToastUtils.showShort("onPaying！");
            }

            @Override
            public void onPayFail() {
                LoadingUtils.hide();
                ToastUtils.showShort("支付失败");
            }

            @Override
            public void onPayCancel() {
                LoadingUtils.hide();
                ToastUtils.showShort("支付取消");
                ActivityStackUtil.finishTopActivity();
            }

            @Override
            public void onPayConnectError() {
                LoadingUtils.hide();
                ToastUtils.showShort("onPayConnectError！");
            }
        });
        payAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, paySign);
    }*/

    /* 支付完成回调接口 */
    /*private void paySuccess(GenerateOrderParamVO orderParamVO){
        NetUtils.orderPaySuccess(orderParamVO, new MyObserver<String>(this) {
            @Override
            public void onSuccess(String result) {
                LoadingUtils.hide();
                //通知刷新购物车
                EventBusUtils.post(new EventMessage<>(EventCode.EVENT_1, "EventData"));
                //提示并跳转
                ToastUtils.showShort("支付成功！");
                ActivityStackUtil.finishTopActivity();
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LoadingUtils.hide();
                ToastUtils.showShort(errorMsg);
            }
        });
    }*/

    @OnClick(R.id.coupon_ll)
    void onCouponTvClicked(){
        Intent intent = new Intent();
        intent.putExtra(Keys.DETAIL_COUPON_KEY,1);
        IntentUtils.startActivityForResult(this,CouponActivity.class,intent,Values.REQUEST_CODE_2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null){
            switch (requestCode) {
                case Values.REQUEST_CODE_1:
                    AddressItem item1 = (AddressItem)data.getSerializableExtra(Keys.FROM_ORDER_KEY);
                    if (null != item1){
                        memberReceiveAddressId = item1.getId();
                        setUpUIWithAddressInfo(item1);
                    }
                    break;
                case Values.REQUEST_CODE_2:
                    CouponItem item2 = (CouponItem)data.getSerializableExtra(Keys.FROM_DETAIL_KEY);
                    if (item2 != null) {
                        currentCouponItem = item2;
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
